jQuery && (function ($) {
    /**
     * dialog
     *
     * @param options
     */
    $.dialog = function(options) {
        return $('body').dialog(options);
    }
    $.fn.dialog = function(options) {
        var dialog, mask,
            mask_w = Math.max(this.width(),$(window).width()),
            mask_h = Math.max(this.height(),$(window).height()),
            self = this;
        options = $.extend({
            name: 'dialog',
            title:'Dialog',
            body: '',
            cls:   null,
            style: {},
            mask:  false,
            close: null,
            offset: null,
            align: 'cc',
            timeout: 3,
            callback: null
        }, options);

        if ($('div[name=dialog_' + options.name + ']', this).hasClass('dialog')) {
            dialog = $('div[name=dialog_' + options.name + '].dialog', this);
            // 重置标题和内容
            $('div.box-hd h3', dialog).html(options.title);
            $('div.box-bd', dialog).html(options.body);
            // 遮罩层
            mask = $('div.mask');
            if (options.mask && mask.is('div')) {
                mask.width(mask_w).height(mask_h).css({'z-index': $('*').maxIndex() + 1});
            }
        } else {
            // 遮罩层
            if (options.mask) {
                mask = $('<div class="mask"><br /></div>').width(mask_w).height(mask_h).css({'z-index': $('*').maxIndex() + 1});
                this.append(mask);
            }
            // dialog
            dialog = $([
                '<div name="dialog_' + options.name + '" class="box hide dialog">',
                    '<i class="box-tp"><b></b></i>',
                    '<div class="box-hd">',
                        '<h3>' + options.title + '</h3>',
                        '<div class="box-act"><a href="javascript:;" class="box-close" rel="close"><span>X</span></a></div>',
                    '</div>',
                    '<div class="box-bd">',
                        options.body,
                    '</div>',
                    '<div class="box-ft"></div>',
                    '<i class="box-bt"><b></b></i>',
                '<button type="button" style="width:0px; height:0px; border:none; background:transparent; text-indent:-99999px;" rel="close">Close</button></div>'
            ].join(''));
            this.append(dialog);
        }
        // 添加自定义的 Class
        if (options.cls) dialog.addClass(options.cls);
        // 添加style
        dialog.css($.extend({'z-index': $('*').maxIndex() + 1}, options.style));
        // 调整位置
        $.use('align', function() {
            options.align ? dialog.align(options.align, options.offset) : null;
            // 下拉显示
            dialog.slideDown('fast');
        });

        // 移除遮罩层
        var timer, remove_mask = function() {
            if (options.mask && mask.is('div')) {
                if ($('div.dialog').size() == 0) {
                    mask.remove();
                } else {
                    mask.css({'z-index': Math.max(+$('div.dialog').maxIndex() - 1, 0)});
                }
            }
        }

        var autoclose = false;
        // 倒计时关闭
        if (!isNaN(options.timeout) && +options.timeout > 0) {
            autoclose = true;
            timer = window.setInterval(function(){
                if (+options.timeout <= 0) {
                    window.clearInterval (timer);
                    $('.close, [rel=close]', dialog).click();
                }
                options.timeout--;
            }, 1000);
        }
        // 关闭事件
        $('.close, [rel=close]', dialog).unbind('click').click(function(){
            if (timer) window.clearInterval (timer);
            if ($.isFunction(options.close)) {
                options.autoclose  = autoclose;
                options.removemask = remove_mask;
                options.close.call(dialog, options);
            } else {
                if (autoclose) {
                    dialog.slideUp('fast', function(){
                        $(this).remove(); remove_mask();
                    });
                } else {
                    dialog.remove(); remove_mask();
                }
            }
        });

        // 绑定焦点事件，支持空格直接关闭
        if ($('button.focus',dialog).is('button')) {
            $('button.focus',dialog).focus();
        } else {
            $('button[rel=close]',dialog).focus();
        }
        
        // 回调函数
        if ($.isFunction(options.callback)) options.callback.call(dialog, options);
        return this;
    };
    /**
     * alert
     *
     * @param message
     * @param type
     * @param title
     * @param callback
     * @param timeout
     */
    $.alert = function(message, type, title, callback, timeout) {
        type    = type || 'Alert';
        title   = title || type;
        timeout = timeout || 3;
        var icons   = {
                'Alert': 'msg-attention',
                'Error': 'msg-error',
                'Success': 'msg-ok'
            },
            icon_cls = icons[type] ? icons[type] : 'msg-attention';
        $.dialog({
            name: 'alert', title:title, timeout:timeout, mask:true, body:[
                '<div class="msg msg-strong msg-weak">',
                    '<div class="msg-default ' + icon_cls + '">',
                        '<i class="msg-icon"></i>',
                        '<h4 class="msg-title">' + message + '</h4>',
                    '</div>',
                '</div>'
            ].join(''),
            style:{ width:450 }, close: function(options){
                if ($.isFunction(callback)) callback();
                if (options.autoclose) {
                    this.slideUp('fast', function(){
                        $(this).remove(); options.removemask();
                    });
                } else {
                    this.remove(); options.removemask();
                }
            }
        });
    }
    /**
     * confirm
     *
     * @param message
     * @param callback
     */
    $.confirm = function(message, callback) {
        $.dialog({
            name: 'confirm', title: '确认', mask:true, timeout:0, body:[
                '<div class="msg msg-weak msg-strong">',
                    '<div class="msg-default msg-question">',
                        '<i class="msg-icon"></i>',
                        '<h4 class="msg-title">' + message + '</h4>',
                    '</div>',
                    '<div class="msg-button form">',
                        '<button type="button" class="button-silver focus" rel="submit">' +'确定' + '</button>',
                        '<button type="button" class="button-silver" rel="close">' +'取消' + '</button>',
                    '</div>',
                '</div>'
            ].join(''),
            style:{ width:450 }, callback: function(opt) {
                var dialog = this;
                $('div.msg-button button[rel=submit], div.msg-button button[rel=close]', dialog).click(function(){
                    $('a.box-close', dialog).click();
                    if ($.isFunction(callback))
                        callback($(this).attr('rel')=='submit');
                });

            }
        });
    }
})(jQuery);
